﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Profile;
using System.Data;

using System.Runtime.Caching;
using System.Text.RegularExpressions;


using CooWork.Models;
using CooWork.Core;

namespace CooWork.Services
{
    public static class UserService
    {
        public static int UcId()        {
            ProfileCommon profile = ProfileCommon.Create(Membership.GetUser().UserName, true) as ProfileCommon;
            return profile.CompanyId;
        }

        public static int UdId()
        {
            ProfileCommon profile = ProfileCommon.Create(Membership.GetUser().UserName, true) as ProfileCommon;
            return profile.DepartmentId;
        }

        public static string Uid()
        {
           return  Membership.GetUser().ProviderUserKey.ToString();
        }

        public static System.Guid Ugid()
        {
            return (Guid)Membership.GetUser().ProviderUserKey;
        }


        public static TreeNode GetDepartmentTree()
        {
            var list = UserService.GetDepartmentList(UserService.UcId(), false);
            Dictionary<string, TreeNode> lookup = new Dictionary<string, TreeNode>();
            list.ForEach(x => lookup.Add(x.Userid, new TreeNode(x.Userid, x.Departmentname, x.Id, x.Parentid, true)));

            foreach (var item in lookup.Values)
            {
                TreeNode proposedParent;
                int pid = item.ParentId ?? 0;
                if (lookup.TryGetValue("department_" + pid, out proposedParent))
                {
                    //item.Parent = proposedParent;              
                    proposedParent.Add(item);
                }
            }
            var r = lookup.Values.Where(x => x.Parent == null).SingleOrDefault();

            return r;
        }



        public static void updateUserInfo(int cid, int did, string ActualName,Guid userid)
        {
            string sql="update [aspnet_Users] set cid={0} , did={1} ,ActualName='{2}' where UserId ='{3}' ";
            sql=string.Format(sql,cid,did,ActualName,userid);
            DataProvider.ExecuteNonQuery(sql);
        }



        public static string GetTreeJson(TreeNode tn)
        {
            if (tn == null) return "";

            string jsonStr = @"{
	    ""data"" : """+tn.Tname+@""",	
	    ""attr"" : { ""tag"" : """ + tn.ID + @""" },""state"" : ""closed"",""children"" : [ <4> ]	}";

            //clear id   ""attr"" : { ""id"" : """ + tn.ID + @""", ""tag"" : """ + tn.ID + @""" },""state"" : ""closed"",""children"" : [ <4> ]	}";

            string ret = string.Empty;
            string childstr = string.Empty;
            ret = jsonStr;

            if (tn.Count > 0)
            {
                foreach (TreeNode t in tn.Children)
                {
                    childstr += GetTreeJson(t) + ",";
                }
                childstr = childstr.Trim(',');
            }
            if (!string.IsNullOrWhiteSpace(childstr))
            {
                ret = Regex.Replace(ret, @"<4>", childstr, RegexOptions.IgnoreCase);
            }
            else
            {//,""state"" : ""closed""
                ret = Regex.Replace(ret, @",""state""[^,]+(?=,)", "", RegexOptions.IgnoreCase);
                ret = Regex.Replace(ret, @",""children""\s+:\s+\[\s+<4>\s+\]", "", RegexOptions.IgnoreCase);
            }
            return ret;
        }



        public static List<CUserList> GetDepartmentList(int cid, bool reset)
        {
            string key = "CompanyDepartmentList_" + cid;
            var obj = MemoryCache.Default.Get(key);
            if (obj == null || reset)
            {
                List<CUserList> lcist = new List<CUserList>();

                string sql = string.Format(@"SELECT  *
                                      FROM 
                                    [CooWork].[dbo].[Department] where cid={0}", cid);

                DataTable dt = DataProvider.GetDataTable(sql);
                foreach (DataRow dr in dt.Rows)
                {
                    int? p = null;
                    if (dr["parentId"] != DBNull.Value)
                    {      
                        p = Convert.ToInt32(dr["parentId"]);
                    }

                    lcist.Add(new CUserList(
                        "department_" + dr["id"].ToString(),
                        "department_" + dr["id"].ToString(),
                          Convert.ToInt32(dr["id"]),p,cid,dr["DepartmentName"].ToString()
                        ));
                }

                //cache
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30);
                if (reset) MemoryCache.Default.Remove(key);
                MemoryCache.Default.Add(new CacheItem(key, lcist), policy);

            }

            return (MemoryCache.Default[key] as List<CUserList>);
        }



        /// <summary>
        /// 获取公司部门及人员数据,缓存
        /// </summary>
        /// <param name="cid"></param>
        /// <param name="reset"></param>
        /// <returns></returns>
        public static List<CUserList> GetCUserList(int cid,bool reset)
        {
            string key = "CompanyUserList_" + cid;
            var obj = MemoryCache.Default.Get(key);

            if (obj == null||reset)
            {
                List<CUserList> lcist = new List<CUserList>();

                string sql = string.Format(@"select aa.userid,aa.ActualName,aa.username,bb.id,bb.parentid,aa.cid,bb.DepartmentName,bb.leader from
                                    (SELECT  * from 
                                     [CooWork].[dbo].[aspnet_Users]     where cid={0})  aa 
                                     inner join 
                                    (SELECT  *
                                      FROM 
                                    [CooWork].[dbo].[Department] where cid={1} ) bb on aa.did=bb.id order by bb.id", cid, cid);

                DataTable dt = DataProvider.GetDataTable(sql);
                int ppid;
                int? pid = null;
                foreach (DataRow dr in dt.Rows)
                {
                    if (int.TryParse(dr["parentid"].ToString(), out ppid))
                    {
                        pid = ppid;
                    }
                    var uname =  dr["ActualName"].ToString();
                    if (dr["userid"].ToString() == dr["leader"].ToString())
                    {
                        uname += "(C)";
                    }
                    lcist.Add(new CUserList(dr["userid"].ToString(),uname,
                        Convert.ToInt32(dr["id"]), pid, Convert.ToInt32(dr["cid"]), dr["DepartmentName"].ToString())
                        );
                }
                //cache
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30);
                if (reset) MemoryCache.Default.Remove(key);
                MemoryCache.Default.Add(new CacheItem(key, lcist), policy);

            }

            return (MemoryCache.Default[key] as List<CUserList>);
        }






   }


    

    public class CUserList
    {
        public string Userid { get;set; }
        public string Username { get; set; }
        public string Departmentname        {            get;            set;       }      
        public int Id { get; set; }
        public int? Parentid { get; set; }
        public int Cid { get; set; }

        public CUserList(string userid, string username, int id, int? parentid, int cid,string departmentname)
        {
            this.Userid = userid;
            this.Username = username;
            this.Id = id;
            this.Parentid = parentid;
            this.Cid = cid;
            this.Departmentname = departmentname;
        }
    }




    public static class z
    {
        public static int GetZInt(string s)
        {
            int ret = 0;
            if (int.TryParse(s, out ret))
            {
                return ret;
            }
            return 0;
        }

        public static string ContentSize(double len)
        {
            string[] sizes = { "B", "KB", "MB", "GB" };
          
            int order = 0;
            while (len >= 1024 && order + 1 < sizes.Length)
            {
                order++;
                len = len / 1024;
            }
            // Adjust the format string to your preferences. For example "{0:0.#}{1}" would
            // show a single decimal place, and no space.
            string result = String.Format("{0:0.##} {1}", len, sizes[order]);

            return result;
        }

    }

   


    public static class Extensions
    {
        public static string EmptyIfNull(this object value)
        {
            if (value == null)
                return "";
            return value.ToString();
        }




    }
}